package com.github.baichuan.application.scaffold.domain.application;

import com.github.baichuan.application.scaffold.dto.realm.RealmForm;
import com.github.baichuan.application.scaffold.jpa.application.ApplicationRepository;
import com.github.baichuan.application.scaffold.jpa.application.RealmRepository;
import com.github.baichuan.web.dto.Result;
import com.github.baichuan.web.error.NoSuchEntityException;
import com.github.baichuan.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class RealmService {

    @Autowired
    private RealmRepository repository;
    @Autowired
    private ApplicationRepository applicationRepository;
    @Autowired
    private SnowFlake snowFlake;

    public Realm find(String id){
        return repository.findById(id).orElseThrow(() -> new NoSuchEntityException());
    }

    public List<Realm> findAll(){
        return repository.findAll();
    }

    public Page<Realm> query(Pageable pageable){
        return repository.findAll(pageable);
    }

    public Result add(RealmForm form){
        if(repository.findByName(form.getName().trim()).isPresent()){
            return Result.fail("应用域名称重复");
        }

        Realm realm = new Realm();
        realm.setId(snowFlake.nextBase62Id().substring(6));
        realm.setName(form.getName().trim());
        repository.save(realm);

        return Result.success("应用域创建成功", realm.getId());
    }

    public Result edit(String id, RealmForm form){
        Optional<Realm> duplicateName = repository.findByName(form.getName().trim());
        if(duplicateName.isPresent() && !duplicateName.get().getId().equals(id)){
            return Result.fail("应用域名称重复");
        }

        Realm realm = find(id);
        realm.setName(form.getName().trim());
        repository.save(realm);

        return Result.success("应用域保存成功");
    }

    public Result remove(String id){
        Realm realm = find(id);

        if(applicationRepository.findByRealm(realm).size() > 0){
            return Result.fail("当前域下存在应用不能删除");
        }

        repository.delete(realm);
        return Result.success("应用域删除成功");
    }
}
